import axios from 'axios'
import routerIndex from '../router/index'
//axios.defaults.withCredentials = true;

var baseUrl
var cameraUrl
async function requestServerIPandPort() {
  baseUrl = localStorage.getItem('baseUrl')
  cameraUrl = localStorage.getItem('cameraUrl')
  if(baseUrl == null ||cameraUrl == null)
  {
    baseUrl = "http://127.0.0.1:8081/WebContent"
    cameraUrl = "http://127.0.0.1:10810/nvc/LiveNVR001/api/v1"
  }
  await axios.get('/serverconfig.json').then((result) => {
    localStorage.setItem('baseUrl', result.data.baseUrl)
    localStorage.setItem('cameraUrl', result.data.cameraUrl)
    localStorage.setItem('qrcode', result.data.qrcode)
    baseUrl = localStorage.getItem('baseUrl')
    cameraUrl = localStorage.getItem('cameraUrl')
  }).catch((error) => {

  })
}
requestServerIPandPort()


// 添加请求拦截器
axios.interceptors.request.use(config => {
  // 在发送请求之前做某事，比如说 设置token
  if(sessionStorage.token != undefined ||sessionStorage.token != null)
  {
    //config.headers['Content-Type'] ='application/json';
    //滤出
    if(config.url.indexOf("nvc/LiveNVR") != -1||config.url.indexOf("api/v1") != -1 )
    {

    }
    else
    {
      config.headers.common['Authorization'] = 'Bearer '+sessionStorage.token;
    }
  }

  return config;
}, error => {
  // 请求错误时做些事
  return Promise.reject(error);
});

// 添加响应拦截器
axios.interceptors.response.use(response => {

  // 对响应数据做些事
  if (response.status === 200) {
  }
  return response;
}, error => {
  if(error.response.status === 401 )
  {
    if(sessionStorage.loginstate == 'in')
    {
      if(error.response.data.code=='1')//过期
      {
        localStorage.setItem('errorcode', 'expire')
        routerIndex.push('/login');
      }
      else if(error.response.data.code=='2')//多个账号登录
      {
        localStorage.setItem('errorcode', 'accounts')
        routerIndex.push('/login');
      }
    }
    else{
      routerIndex.push('/login');
    }
  }
  return Promise.reject(error.response.data); // 返回接口返回的错误信息
})
var depot={};

depot.get =  function ({ url, data = {}, cb }) {
  url = baseUrl + url;
  // url = "/api" + url;
  let dataStr = ''; //数据拼接字符串
  Object.keys(data).forEach(key => {
    //过滤空字段
    // if (data[key].length > 0 && data[key] !== undefined)
    dataStr += key + '=' + data[key] + '&';
  });
  if (dataStr !== '') {
    dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
    url = url + '?' + dataStr;
  }
  axios({
    method:'GET',
    url:url,
    //withCredentials:true,
  }).then((res)=>{
    if (res.status === 200) {
      let result = res.data;
      cb(result);
    }
  }).catch((error) => {

  });
};
depot.awaitget = function ({ url, data = {}, cb }) {//同步请求数据
  url = baseUrl + url;
  // url = "/api" + url;
  let dataStr = ''; //数据拼接字符串
  Object.keys(data).forEach(key => {
    //过滤空字段
    // if (data[key].length > 0 && data[key] !== undefined)
    dataStr += key + '=' + data[key] + '&';
  });
  if (dataStr !== '') {
    dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
    url = url + '?' + dataStr;
  }
  return new Promise((resolve,reject)=>{
    axios({
      method:'GET',
      url:url,
      //withCredentials:true,
    }).then((res)=>{
      if (res.status === 200) {
        let result = res.data;
        resolve(result)
      }
    }).catch((error) => {
      reject(error)
    });
  })
};

depot.post=  function ({ url, data, cb }) {
  url = baseUrl + url;
  // url = "/api" + url;
  axios({
    method:'POST',
    url:url,
    data:data,
    //withCredentials:true,
    headers:{'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest:function(obj){
      var str = [];
      for(var p in obj){
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
      return str.join("&");
    }
  }).then((res)=>{
    if (res.status === 200) {
      let result = res.data;
      cb(result)
    }
  }).catch((error) => {

  });
};
depot.awaitpost=  function ({ url, data }) {   //同步请求数据
  url = baseUrl + url;
  // url = "/api" + url;
  return new Promise((resolve,reject)=>{
    axios({
      method:'POST',
      url:url,
      data:data,
      //withCredentials:true,
      headers:{'Content-Type': 'application/x-www-form-urlencoded'},
      transformRequest:function(obj){
        var str = [];
        for(var p in obj){
          str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        }
        return str.join("&");
      }
    }).then((res)=>{
      if (res.status === 200) {
        let result = res.data;
        resolve(result)
      }
    }).catch((error) => {
      reject(error)
    });
  })

}

depot.cget =  function ({ url, data = {}, cb }) {
  url = cameraUrl + url;
  // url = "/api" + url;
  let dataStr = ''; //数据拼接字符串
  Object.keys(data).forEach(key => {
    //过滤空字段
    // if (data[key].length > 0 && data[key] !== undefined)
    dataStr += key + '=' + data[key] + '&';
  });
  if (dataStr !== '') {
    dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
    url = url + '?' + dataStr;
  }
  axios({
    method:'GET',
    url:url,
    //withCredentials:true,
  }).then((res)=>{
    if (res.status === 200) {
      let result = res.data;
      cb(result);
    }
  }).catch((error) => {

  });
};
depot.cpost=  function ({ url, data, cb }) {
  url = cameraUrl + url;
  // url = "/api" + url;
  axios({
    method:'POST',
    url:url,
    data:data,
    //withCredentials:true,
    headers:{'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest:function(obj){
      var str = [];
      for(var p in obj){
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
      return str.join("&");
    }
  }).then((res)=>{
    if (res.status === 200) {
      let result = res.data;
      cb(result)
    }
  }).catch((error) => {

  });
};
depot.filepost=  function ({ url, data, cb }) {
  url = baseUrl + url;
  // url = "/api" + url;
  axios({
    method:'POST',
    url:url,
    data:data,
    //withCredentials:true,
    headers:{"Content-Type": "multipart/form-data" },
  }).then((res)=>{
    if (res.status === 200) {
      let result = res.data;
      cb(result)
    }
  }).catch((error) => {

  });
};
export default () => {
  window.depot = depot;
};


// export default (url = '', data = {}, type = 'GET', method = 'fetch') => {
//     type = type.toUpperCase();
//     url = "/api" + url;

//     //将对象解析成get后面？&形式的参数
//     if (type === 'GET' || type === 'DOWNLOAD' || type === 'UPLOAD') {
//         let dataStr = ''; //数据拼接字符串
//         Object.keys(data).forEach(key => {
//             //过滤空字段
//             // if (data[key].length > 0 && data[key] !== undefined)
//             dataStr += key + '=' + data[key] + '&';
//         });
//         if (dataStr !== '') {
//             dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
//             url = url + '?' + dataStr;
//         }
//     } else if (type == "RESTFUL") {
//         url += data;
//     }

//     return new Promise((resolve, reject) => {
//         switch (type) {
//             case "UPLOAD": {
//                 resolve(url);
//             }
//                 break;
//             case "GET": {
//                 axios.get(url).then(async (res) => {
//                     resolve(res.data);
//                 }).catch(async (err) => {
//                     reject(err);
//                 })
//             }
//                 break;
//             case "POST": {
//                 url = url //+ "?XDEBUG_SESSION_START=PHPSTORM";
//                 axios.post(url, data).then(async (res) => {
//                     resolve(res.data);
//                 }).catch(async (err) => {
//                     reject(err);
//                 });

//             }
//                 break;
//             case "DOWNLOAD": {
//                 window.open(url);
//                 resolve(url);
//             }
//                 break;
//             case "RESTFUL":{
//                 axios.get(url).then(async (res) => {
//                     resolve(res.data);
//                 }).catch(async (err) => {
//                     reject(err);
//                 })
//             }

//         }

//     })
// };
